package com.uchengwang.ui.cm_ui.umsg.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.widget.MsgView;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.functions.jpush.JpushSetAlisTagUtil;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.basefm.FragmentUU;
import com.uchengwang.ui.base_ui.bean.TabEntity;
import com.uchengwang.ui.base_ui.listener.HasUnReadMsgListener;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.cm_ui.login.LoginHttp.LoginHttpManager;
import com.uchengwang.ui.cm_ui.me.ui.MySettingActivity;
import com.uchengwang.ui.cm_ui.release.ui.FastReleaseActivity;
import com.uchengwang.ui.cm_ui.rychat.manager.RongChatManager;
import com.uchengwang.ui.cm_ui.ucity.presenter.HttpCityPresenter;
import com.uchengwang.ui.cm_ui.umsg.fragment.ClubFragmentMe;
import com.uchengwang.ui.cm_ui.umsg.fragment.ClubFragmentRelease;
import com.uchengwang.ui.cm_ui.uu.ui.QRScanActivity;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.SwitchAccountUtils;
import com.uchengwang.ui.utils.UCommonUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created by Mizlicai on 2017/9/3.
 * 切换到社团账户时的简约界面 到这最后
 */

public class ClubMainActivity extends AllBaseActivity implements IUnReadMessageObserver {

    public static boolean isForeground = false;//极光推送
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static boolean isResumeChange = false;//未登录 跳转到登录界面也未登录 在返回主界面

    // 定义数组来存放Fragment界面
    private Fragment[] fragments = null;

    private FragmentUU fragmentMsg;
    private ClubFragmentRelease fragmentRelease;
    private ClubFragmentMe fragmentMe;

    // 定义数组来存放选中按钮图片
    private final int mImgSelect[] = {
            R.drawable.club_circle_tab_pressed,
            R.drawable.icon_tab_release_check,
            R.drawable.umy_tab_pressed};

    // 定义数组来存放未选中按钮图片
    private final int mImgUnSelect[] = {
            R.drawable.club_circle_tab_normal,
            R.drawable.icon_tab_release_normal,
            R.drawable.umy_tab_normal};

    // Tab选项卡的文字
    private final String mTabTitle[] = {"", "",""};
    private ArrayList<CustomTabEntity> mTabData = new ArrayList<>();

    private FrameLayout realtabcontent;
    private CommonTabLayout ctl_main_tab;
    private ActivityTitleBar titleBar;
    private long reFreshTime;//刷新时间
    private ImageView clubMain_bg;

    private int currentIndex = 0, preIndex;//当前的fragment角标 切换到当前角标的上一个角标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_club_main);

        EventBus.getDefault().register(this);
        initView();
    }

    private void initView(){
        realtabcontent = (FrameLayout) findViewById(R.id.realtabcontent);
        ctl_main_tab = (CommonTabLayout) findViewById(R.id.ctl_main_tab);
        titleBar = (ActivityTitleBar) findViewById(R.id.clubMain_titleBar);
        clubMain_bg = (ImageView) findViewById(R.id.clubMain_bg);
        clubMain_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clubMain_bg.setVisibility(View.GONE);
            }
        });

        ctl_main_tab.setNoTitleImageSize(50);

        initData();

        //检查版本更新
        HttpCityPresenter.getPresenter().sysVersion(ClubMainActivity.this, UCommonUtil.getUtil().GetVersion(ClubMainActivity.this));

        LoginHttpManager.getManager().downloadMyFriends(ClubMainActivity.this);
        LoginHttpManager.getManager().downloadMyGroups(ClubMainActivity.this);

        setJPush();


    }

    private void initData(){
        for (int i = 0; i < mTabTitle.length; i++) {
            mTabData.add(new TabEntity(mTabTitle[i], mImgSelect[i], mImgUnSelect[i]));
        }

        fragmentMsg = new FragmentUU();
        fragmentRelease = new ClubFragmentRelease();
        fragmentMe = new ClubFragmentMe();
        fragments = new Fragment[]{fragmentMsg, fragmentRelease,fragmentMe};


        ctl_main_tab.setTabData(mTabData);
        ctl_main_tab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                changeFragment(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        titleBar.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });

        //首次进入社团账号 提示如何返回个人账号
        boolean isBackPerson = SPUtils.getPreferences(this).getBoolean(BaseConfig.IS_BACK_PERSON);
        if (!isBackPerson){
            clubMain_bg.setVisibility(View.VISIBLE);
            ImageManager.getInstance().loadImage(this, clubMain_bg, R.drawable.guide_club_to_per, ImageManager.ImageType.NARMOL);
            SPUtils.getPreferences(this).putBoolean(BaseConfig.IS_BACK_PERSON, true);
        }

        fragmentMsg.setTitleBarHide(true);
        init();
    }

    private void init(){
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };

        //更新未读消息
        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);
    }

    private void setJPush(){
        //极光设置alis
        if (UCommonUtil.getUtil().getId() >0){//登录状态 设置alis
            if (JPushInterface.isPushStopped(this)){
                JPushInterface.resumePush(this);
            }else {
                JpushSetAlisTagUtil.getUtil().setAlis(this);
            }
        }else {
            //未登录
            JpushSetAlisTagUtil.getUtil().setNullAlis(this);
        }

        //设置tag
        JpushSetAlisTagUtil.getUtil().setClubTags(this);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        getSupportFragmentManager().beginTransaction().replace(R.id.realtabcontent, fragments[currentIndex]).commit();
        ctl_main_tab.setCurrentTab(currentIndex);
        titleBar.setTitle("社团消息", 0);
    }

    private void changeFragment(int position){

        switch (position){
            case 0:
                titleBar.setTitle("社团消息", 0);
//                titleBar.setImageRightGone();
                titleBar.setImageRight(R.drawable.icon_msg_saoyisao, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (UCommonUtil.getUtil().isNeedLogin(ClubMainActivity.this, false)){
                            return;
                        }
                        startActivity(new Intent(ClubMainActivity.this, QRScanActivity.class));
                    }
                });
                break;
            case 1:
                titleBar.setTitle("社团发布", 0);
                titleBar.setImageRightGone();
                break;
            case 2:
                titleBar.setTitle("社团主页", 0);
                titleBar.setImageRight(R.drawable.setting_image, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ClubMainActivity.this, MySettingActivity.class);
                        startActivity(intent);
                    }
                });
                break;
        }

        if (currentIndex != position){
            if (position ==1){
                //发布界面
                Intent intent = new Intent(this, FastReleaseActivity.class);
                startActivity(intent);
                return;
            }


            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!fragments[position].isAdded()) {    // 先判断是否被add过
                transaction.hide(fragments[currentIndex]).add(R.id.realtabcontent, fragments[position]).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(fragments[currentIndex]).show(fragments[position]).commit(); // 隐藏当前的fragment，显示下一个
            }
            preIndex = currentIndex;
            currentIndex = position;
        }


    }

    /**
     * 隐藏某个Fragment所在角标的红点
     * */
    public void hideDot(int index){
        ctl_main_tab.hideMsg(index);
    }
    /**
     * 显示某个Fragment所在角标的红点
     * */
    public void showDot(int index){
        ctl_main_tab.showDot(index);
    }

    /**
     * 获取当前Fragment角标的未读消息数
     * */
    public int getNoReadMsg(int index){
        MsgView view = ctl_main_tab.getMsgView(index);
        String msgNum = view.getText().toString();
        if (TextUtils.isEmpty(msgNum)){
            return -1;
        }
        return Integer.valueOf(msgNum);
    }

    /**
     * 收到EventBus信息
     * */
    public void onEvent(Boolean isRefresh) {
        if (isRefresh != null && isRefresh){
            if (fragmentMsg != null  && fragmentMsg.getActivity() != null && !fragmentMsg.getActivity().isFinishing()) {
                fragmentMsg.initData(true);
            }
        }
    }


    @Override
    public void onCountChanged(int count) {
        if (count > 0) {
            ctl_main_tab.showMsg(0, count);
        } else {
            ctl_main_tab.hideMsg(0);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //判断融云
        if (UCommonUtil.getUtil().isLogin() && (RongIM.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED
                || RongIM.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT)){
            RongChatManager.getUtils().getTokenAdnLink(this, null);
        }

        /**
         * 每隔一定的时间去查看享说和我的界面有没有消息更新
         * */
        if ((System.currentTimeMillis()- reFreshTime)/1000/60 >1){
            getUnReadMsg();
        }
        MobclickAgent.onResume(this);
        isForeground = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        isForeground = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResumeChange = false;
        BaseConfig.isRelease = false;
        UChengApplication.isAccountChange = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取享说和我的未读消息
     * */
    private void getUnReadMsg(){

        if (fragmentMe != null && fragmentMe.getActivity() != null){
            fragmentMe.getUnReadMsg(new HasUnReadMsgListener() {
                @Override
                public void unReadMsg(int count) {
                    if (count >0){
                        ctl_main_tab.showDot(3);
                    }
                }
            });
        }
        reFreshTime = System.currentTimeMillis();
    }

    /**
     * 退出程序但不销毁
     * 参数为false——代表只有当前activity是task根，指应用启动的第一个activity时，才有效;
     参数为true——则忽略这个限制，任何activity都可以有效。
     * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //切换回个人
    private void back(){
        //做切换回个人的操作
        SwitchAccountUtils.getUtils().toPersonAccount(ClubMainActivity.this);
    }
}
